package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.AddressService;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private AddressMapper AddressMapper;


    @Override
    public void save(Order order) {
        //保存订单明细表信息 要保存的菜品明细就是购物车中的
        //1.获取到当前的登录用户
        User user = UserHolder.get();
        //2.查询到当前用户的购物车
        List<Cart> cartList = cartService.find();
        if (CollectionUtil.isEmpty(cartList)) {
            throw new CustomException("购物车是空的,您还没有下单");
        }
        //3.根据前端传递的地址id查询地址
        Long addressId = order.getAddressId();
        Address address = AddressMapper.selectById(addressId);
        if (address == null) {
            throw new CustomException("请选择配送地址");
        }
        //4. 手动使用雪花算法生一个订单id
        Long orderId = IdWorker.getId();//mybatisplus工具类生成雪花算法的id
        BigDecimal total = new BigDecimal(0);//合计金额,因为单价是BigDecimal的,所以这里也定义成BigDecimal
        //total += Number * Amount
        //5.遍历购物车,得到购物车中的商品信息 生成订单详情
        for (Cart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());//名称
            orderDetail.setOrderId(orderId);//订单id
            orderDetail.setDishId(cart.getDishId());//菜品id
            orderDetail.setSetmealId(cart.getSetmealId());//套餐id
            orderDetail.setDishFlavor(cart.getDishFlavor());//口味
            orderDetail.setNumber(cart.getNumber());//数量
            orderDetail.setAmount(cart.getAmount());//金额
            orderDetail.setImage(cart.getImage());//图片

            //凑齐了属性保存到数据库
            orderDetailMapper.insert(orderDetail);
            //计算总金额
            total = total.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));
        }
        //保存订单表信息
        order.setId(orderId);//id
        order.setNumber(orderId + "");//订单号
        order.setStatus(2);//订单状态
        order.setUserId(user.getId());//下单用户id
        order.setOrderTime(new Date());//下单时间
        order.setCheckoutTime(new Date());//支付时间
        order.setAmount(total);//实收金额
        order.setUserName(user.getName());//用户名
        order.setPhone(address.getPhone());//手机号
        order.setAddress(address.getDetail());//地址
        order.setConsignee(address.getConsignee());

        orderMapper.insert(order);

        //清空此用户购物车
        cartService.clean();
    }

    @Override
    public Page<Order> findByPage(Integer pageNum, Integer pageSize) {
        Page<Order> page = new Page<>(pageNum, pageSize);
        //倒序排序
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getId,UserHolder.get().getId())
                .orderByDesc(Order::getId);
        page = orderMapper.selectPage(page, wrapper);
        List<Order> records = page.getRecords();
        for (Order order : records) {
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId, order.getId());
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
            order.setOrderDetails(orderDetailList);
        }

        return page;
    }

    @Override
    public Page<Order> findOrder(Integer pageNum, Integer pageSize, String number, Date beginTime, Date endTime) {
        //1.封装page对象
        Page<Order> page = new Page<>(pageNum, pageSize);
        //2.封装查询条件

        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotEmpty(number), Order::getNumber, number)
                .ge(beginTime != null, Order::getOrderTime, beginTime)
                .le(endTime!=null,Order::getCheckoutTime,endTime);
        // .between(StringUtils.isNotEmpty(beginTime) && StringUtils.isNotEmpty(endTime), Order::getOrderTime, beginTime, endTime);
        page = orderMapper.selectPage(page, wrapper);
        return page;

    }
}
